package com.maoslv.controller;

import com.maoslv.aop.LogAnnotation;
import com.maoslv.dto.Result;
import com.maoslv.pojo.User;
import com.maoslv.service.user.UserService;
import com.maoslv.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Scope("request")
public class RegisterController {

    @Autowired
    UserService userService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("/register")
    @LogAnnotation(operator = "注册用户")
    public Result register(@RequestBody User user) {
        User queryUser = userService.queryUsername(user.getUsername());
        if (queryUser == null) {
            if (redisUtil.get(user.getUsername() + "-email") != null || !redisUtil.get(user.getUsername() + "-email").equals("")) {
                if (!redisUtil.get(user.getUsername() + "-email").equals(user.getCode())) {
                    return Result.fail("验证码有误");
                }
            } else {
                return Result.fail("验证码已过期");
            }
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            int i = userService.registerUser(user);
            if (i > 0) {
                return Result.succ("注册成功",null);
            }
        }
        return Result.fail("用户名已存在");
    }
}
